<template>
  <el-upload ref="UploadRef" :file-list="fileList" :autoUpload="false" :onChange="onChange" :onExceed="onExceed" :onRemove="onRemove" multiple :limit="maxLength" :accept="accept">
    <el-button type="primary"> 上传文件 </el-button>
  </el-upload>
</template>
<script lang="ts" setup>
import {ref} from 'vue';
import {ElMessage, ElUpload, UploadFile} from 'element-plus';

const props = defineProps<{
  modelValue: UploadFile[];
  clearable?: boolean;
  disabled?: boolean;
  placeholder?: string;
}>();

const UploadRef = ref<InstanceType<typeof ElUpload>>();
const fileList = ref<UploadFile[]>(props.modelValue);
const maxLength = 10;
const accept = '.pdf';

/** 文件上传 */
const onChange = (file: UploadFile) => {
  if (accept.split(',').some(item => file.name.endsWith(item))) {
    fileList.value.push(file);
  } else {
    ElMessage.warning(`请上传${accept}格式文件`);
    UploadRef.value?.handleRemove(file);
  }
};
/** 文件超出超出 */
const onExceed = () => {
  ElMessage.warning(`最多上传${maxLength}个文件`);
};
/** 文件删除 */
const onRemove = (file: UploadFile) => {
  const delIndex = fileList.value.findIndex(item => item.uid === file.uid);
  fileList.value.splice(delIndex, 1);
};
</script>
